/**
 * ResulpTabPanel.java
 *
 * Created on 07.12.2008, 11:19:29
 */
package trim.gui.testing.components;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import trim.common.inputdata.MaterialStock;
import trim.common.result.Pattern;
import trim.gui.testing.AppState;
import trim.gui.testing.export.ExportManager;
import trim.gui.testing.models.IRowManipulationTableModel;
import trim.gui.testing.models.ProductionTableModel;
import trim.gui.testing.models.PropertiesTableModel;
import trim.gui.testing.models.ResultTableModel;
import trim.gui.testing.models.UsedMaterialsTableModel;
import trim.gui.testing.objects.ResultsListItem;

/**
 *
 * @author Дмитрий
 */
public class ResultTabPanel extends javax.swing.JPanel
{

  ResultsListItem trimResult;
  ResultTableModel resultModel;
  ProductionTableModel requestFormatsModel;
  UsedMaterialsTableModel requestMaterialsModel;
  PropertiesTableModel propertiesTableModel;

  public ResultTabPanel(ResultsListItem trimResult)
  {
    this.trimResult=trimResult;
    preInitComponents();
    initComponents();
    afterInitComponent();
  }

  /**
   * Обработка перед настройко визуальных компонент
   */
  private void preInitComponents()
  {
    requestFormatsModel=new ProductionTableModel(trimResult.getInputData().getFormatOrderList(),
        trimResult.getTrimmedFormatOrders());
    List<MaterialStock> lmc=new ArrayList();
    Map<Integer,MaterialStock> m=new TreeMap();
    for(Pattern p:trimResult)
    {
      MaterialStock mc=m.get(p.getMaterial().getLength());
      if(mc==null)
      {
        mc=new MaterialStock(p.getMaterial(),0);
        m.put(p.getMaterial().getLength(),mc);
      }
      mc.setCount(mc.getCount()+p.getCount());
    }
    for(MaterialStock mc:m.values())
      lmc.add(mc);
    requestMaterialsModel=new UsedMaterialsTableModel(trimResult.getInputData().getMaterialStockList(),lmc);
    propertiesTableModel=new PropertiesTableModel(false);
    resultModel=new ResultTableModel(trimResult);
  }

  /**
   * Обработка после настройко визуальных компонент
   */
  private void afterInitComponent()
  {
    lbMaterials.setText(trimResult.getUsedMaterialsCount()+"");
    lbTail.setText(trimResult.getTail()+"");
    lbPatterns.setText(trimResult.size()+"");
    DecimalFormat f=new DecimalFormat("#,##0.00");
    lbEfficiency.setText(f.format(trimResult.getEfficiency()*100)+"%");
    for(int i=0;i<4;i++)
      trimTable.getColumnModel().getColumn(i).setPreferredWidth(100);
    
		TableColumn col=trimTable.getColumnModel().getColumn(1);
		col.setPreferredWidth(400);
		col.setCellRenderer(new PatternCellRenderer());
		trimTable.setRowHeight(30);

  }
	private class PatternCellRenderer extends JPanel implements TableCellRenderer
	{
	private ArrayList<int[]> displayList;
		@Override
		public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
		{
			displayList=(ArrayList<int[]>)value;
			//this.setText(value+"-qweqwe");
	
			return this;
		}

		@Override
		public void paint(Graphics g)
		{
			super.paint(g);
			Rectangle r=g.getClipBounds();			
//			g.setColor(Color.RED);
//			g.fillRect(r.x,r.y,r.width,r.height);
			//g.drawString(r.x+" "+r.y+" "+r.width+""+r.height,15,15);
			int w=displayList.get(0)[0];
			//размер одной единицы
			double m=(r.getWidth()-4)/w;
			int shift=2;
			//Font font=g.getFont();
			g.setFont(new Font(Font.SANS_SERIF,0,11));
			FontMetrics fm=g.getFontMetrics();
			for(int[] x:displayList.subList(1,displayList.size()))
			{
				for(int i=0;i<x[1];i++){
					g.setColor(Color.RED);
					w=(int)(x[0]*m);
					int cx=shift+w/2;
					int cy=2+(r.height-5)/2;
					g.fillRect(shift,2,w,r.height-5);
					g.setColor(Color.black);
					g.drawRect(shift,2,w,r.height-5);
					shift+=w;
					String fmt=x[0]+"";
					Rectangle2D rs=fm.getStringBounds(fmt,g);
					if(rs.getWidth()<w)
						g.drawString(fmt,cx-(int)(rs.getWidth()/2),cy+(int)(rs.getHeight()/2)-2);
				}
			}
		}

	}

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    resultSplitPane = new javax.swing.JSplitPane();
    TrimPanel = new javax.swing.JPanel();
    totalsTrimPanel = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    lbMaterials = new javax.swing.JLabel();
    lbTail = new javax.swing.JLabel();
    lbPatterns = new javax.swing.JLabel();
    lbEfficiency = new javax.swing.JLabel();
    trimScrollPane = new javax.swing.JScrollPane();
    trimTable = new javax.swing.JTable();
    sourceSplitPane = new javax.swing.JSplitPane();
    sourceTabbedPane = new javax.swing.JTabbedPane();
    formatsScrollPane = new javax.swing.JScrollPane();
    formatsTable = new javax.swing.JTable();
    materialsScrollPane = new javax.swing.JScrollPane();
    materialsTable = new javax.swing.JTable();
    propertiesScrollPane = new javax.swing.JScrollPane();
    propertiesTable = new javax.swing.JTable();
    jToolBar1 = new javax.swing.JToolBar();
    jLabel5 = new javax.swing.JLabel();
    btExportXML = new javax.swing.JButton();

    resultSplitPane.setResizeWeight(0.75);
    resultSplitPane.setOneTouchExpandable(true);

    TrimPanel.setPreferredSize(new java.awt.Dimension(600, 379));

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
    jLabel1.setText("Materials");

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
    jLabel2.setText("Tail");

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
    jLabel3.setText("Patterns");

    jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
    jLabel4.setText("Efficiency");

    lbMaterials.setText("jLabel5");

    lbTail.setText("jLabel6");

    lbPatterns.setText("jLabel7");

    lbEfficiency.setText("jLabel8");

    javax.swing.GroupLayout totalsTrimPanelLayout = new javax.swing.GroupLayout(totalsTrimPanel);
    totalsTrimPanel.setLayout(totalsTrimPanelLayout);
    totalsTrimPanelLayout.setHorizontalGroup(
      totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(totalsTrimPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel1)
          .addComponent(jLabel2))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(lbMaterials)
          .addComponent(lbTail))
        .addGap(71, 71, 71)
        .addGroup(totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(totalsTrimPanelLayout.createSequentialGroup()
            .addComponent(jLabel4)
            .addGap(18, 18, 18)
            .addComponent(lbEfficiency))
          .addGroup(totalsTrimPanelLayout.createSequentialGroup()
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(lbPatterns)))
        .addContainerGap(267, Short.MAX_VALUE))
    );
    totalsTrimPanelLayout.setVerticalGroup(
      totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(totalsTrimPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(jLabel3)
          .addComponent(lbMaterials)
          .addComponent(lbPatterns))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(totalsTrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(jLabel4)
          .addComponent(lbTail)
          .addComponent(lbEfficiency)))
    );

    trimTable.setAutoCreateRowSorter(true);
    trimTable.setModel(resultModel);
    trimScrollPane.setViewportView(trimTable);

    javax.swing.GroupLayout TrimPanelLayout = new javax.swing.GroupLayout(TrimPanel);
    TrimPanel.setLayout(TrimPanelLayout);
    TrimPanelLayout.setHorizontalGroup(
      TrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(totalsTrimPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(trimScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE)
    );
    TrimPanelLayout.setVerticalGroup(
      TrimPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(TrimPanelLayout.createSequentialGroup()
        .addComponent(totalsTrimPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(trimScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE))
    );

    resultSplitPane.setLeftComponent(TrimPanel);

    sourceSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
    sourceSplitPane.setResizeWeight(0.75);
    sourceSplitPane.setPreferredSize(new java.awt.Dimension(200, 839));

    sourceTabbedPane.setPreferredSize(new java.awt.Dimension(457, 300));

    formatsTable.setAutoCreateRowSorter(true);
    formatsTable.setModel(requestFormatsModel);
    formatsTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        formatsTableMouseClicked(evt);
      }
    });
    formatsScrollPane.setViewportView(formatsTable);

    sourceTabbedPane.addTab("Форматы", formatsScrollPane);

    materialsTable.setAutoCreateRowSorter(true);
    materialsTable.setModel(requestMaterialsModel);
    materialsTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        materialsTableMouseClicked(evt);
      }
    });
    materialsScrollPane.setViewportView(materialsTable);

    sourceTabbedPane.addTab("Материалы", materialsScrollPane);

    sourceSplitPane.setLeftComponent(sourceTabbedPane);

    propertiesScrollPane.setPreferredSize(new java.awt.Dimension(452, 100));

    propertiesTable.setModel(propertiesTableModel);
    propertiesScrollPane.setViewportView(propertiesTable);

    sourceSplitPane.setRightComponent(propertiesScrollPane);

    resultSplitPane.setRightComponent(sourceSplitPane);

    jToolBar1.setRollover(true);

    jLabel5.setText("Export to: ");
    jToolBar1.add(jLabel5);

    btExportXML.setText("XLS");
    btExportXML.setFocusable(false);
    btExportXML.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btExportXML.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btExportXML.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btExportXMLActionPerformed(evt);
      }
    });
    jToolBar1.add(btExportXML);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE)
      .addComponent(resultSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(resultSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE))
    );
  }// </editor-fold>//GEN-END:initComponents

  /**
   * Отображение свойств формата
   * @param evt
   */
  private void formatsTableMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_formatsTableMouseClicked
  {//GEN-HEADEREND:event_formatsTableMouseClicked
    JTable tab=(JTable)evt.getSource();
    int index=tab.convertRowIndexToModel(tab.getSelectedRow());
    if(index<0)
    {
      propertiesTableModel.setObject(null);
    }else
    {
      propertiesTableModel.setObject(((IRowManipulationTableModel)tab.getModel()).getObject(index));
    }
  }//GEN-LAST:event_formatsTableMouseClicked
  /**
   * Отображение свойств материала
   * @param evt
   */
  private void materialsTableMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_materialsTableMouseClicked
  {//GEN-HEADEREND:event_materialsTableMouseClicked
    JTable tab=(JTable)evt.getSource();
    int index=tab.convertRowIndexToModel(tab.getSelectedRow());
    if(index<0)
    {
      propertiesTableModel.setObject(null);
    }else
    {
      propertiesTableModel.setObject(((IRowManipulationTableModel)tab.getModel()).getObject(index));
    }
  }//GEN-LAST:event_materialsTableMouseClicked

  private void btExportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExportXMLActionPerformed
     JFileChooser fileChooser=new JFileChooser(AppState.CURRENT_FILE);
    FileFilter ff=new FileNameExtensionFilter("*.xls","xls");
    fileChooser.setFileFilter(ff);
    int r=fileChooser.showSaveDialog(this);
    if(r==JFileChooser.APPROVE_OPTION)
    {
      try
      {
        File f=fileChooser.getSelectedFile();
        if(!f.getName().toLowerCase().endsWith(".xls"))
          f=new File(f.getAbsolutePath()+".xls");
        AppState.CURRENT_FILE=f.getParentFile();
        FileOutputStream fos=new FileOutputStream(f);
        ExportManager.exportResultToXLS(fos,trimResult);
        fos.close();
        //mainInputData.saveDataToXML(fileChooser.getSelectedFile());
      }catch(Exception ex)
      {
        ex.printStackTrace();
      }
    }
  }//GEN-LAST:event_btExportXMLActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JPanel TrimPanel;
  private javax.swing.JButton btExportXML;
  private javax.swing.JScrollPane formatsScrollPane;
  private javax.swing.JTable formatsTable;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JLabel lbEfficiency;
  private javax.swing.JLabel lbMaterials;
  private javax.swing.JLabel lbPatterns;
  private javax.swing.JLabel lbTail;
  private javax.swing.JScrollPane materialsScrollPane;
  private javax.swing.JTable materialsTable;
  private javax.swing.JScrollPane propertiesScrollPane;
  private javax.swing.JTable propertiesTable;
  private javax.swing.JSplitPane resultSplitPane;
  private javax.swing.JSplitPane sourceSplitPane;
  private javax.swing.JTabbedPane sourceTabbedPane;
  private javax.swing.JPanel totalsTrimPanel;
  private javax.swing.JScrollPane trimScrollPane;
  private javax.swing.JTable trimTable;
  // End of variables declaration//GEN-END:variables
}
